package top.mccat.shirospringboot.shiro.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.mccat.shirospringboot.shiro.realm.UserRealm;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Raven
 * @version 1.0
 * @date 2022/3/7
 */
@Configuration
public class ShiroConfig {
    /**
     * 进行FilterFactoryBean的配置，设置安全管理器
     * @param defaultSecurityManager
     * @return ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultSecurityManager") DefaultWebSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultSecurityManager);
        //设置shiro的内置过滤器
        /**
         * 过滤等级：
         * anon（匿名）无需验证可以直接访问
         * authc（身份验证）必须通过验证才可用
         * user （用户方面），有记住我功能才可用
         * perms （权限方面）拥有某些权限才可访问
         * role （角色方面）拥有某个角色权限才可访问
         */
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add","authc");
        filterMap.put("/user/update","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 进行 DefaultSecurityManager 的配置
     * @param userRealm 传入方法名
     * @return DefaultSecurityManager
     */
    @Bean(name = "defaultSecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userReal") UserRealm userRealm){
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        //关联realm对象
        defaultSecurityManager.setRealm(userRealm);
        return defaultSecurityManager;
    }

    /**
     * realm object method.
     * @return userRealm object.
     */
    @Bean
    public UserRealm userReal(){
        return new UserRealm();
    }
}
